package com.katze.boot.common.config;

import com.katze.boot.plugins.security.JwtTokenProvider;
import com.katze.common.ResponseStatus;
import com.katze.common.ws.core.MessageChannel;
import com.katze.common.ws.core.MessageListener;
import com.katze.common.ws.handler.JwtAuthHandler;
import com.katze.common.ws.protocol.Message;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * WebSocket建立通道认证
 */
@Component
@MessageListener
public class WebSocketHandler implements JwtAuthHandler, MessageChannel {
    private static final Logger log = LoggerFactory.getLogger(WebSocketHandler.class);

    @Override
    public Object doAuthentication(String token, Consumer<Serializable> con) {
        List<Object> data = new ArrayList<>();
        ResponseStatus status = JwtTokenProvider.verify(token, jwt->{
            String username = jwt.getClaim("username").asString();
            con.accept(username);
            return ResponseStatus.OK;
        });
        if(status == ResponseStatus.OK) {
            return data;
        } else {
            throw new IllegalAccessError(status.note());
        }
    }

    @Override
    public void onMessage(Channel channel, Message message) throws Exception {
        // 处理聊天消息
        log.info("[{}] 收到聊天消息: {}", channel.id(), message);
    }
}
